package com.bong.panpan.bongcharttools.fragment;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bong.panpan.bongcharttools.R;
import com.bong.panpan.bongcharttools.adapter.DeviceLinkedListAdapter;
import com.bong.panpan.bongcharttools.ble.BleDevice;
import com.bong.panpan.bongcharttools.ble.BleDeviceState;
import com.bong.panpan.bongcharttools.ble.BleInfo;
import com.bong.panpan.bongcharttools.ble.BleLink;
import com.bong.panpan.bongcharttools.ble.HeartBleLink;
import com.bong.panpan.bongcharttools.custom.BleStateRunnable;
import com.bong.panpan.bongcharttools.custom.MyUtil;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class DeviceFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @InjectView(R.id.list_linked)
    ListView listLinked;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private DeviceLinkedListAdapter adapter;

    public ArrayList<BleDevice> getLinkedDevices() {
        return linkedDevices;
    }

    private ArrayList<BleDevice> linkedDevices = new ArrayList<>();

    private OnDeviceFragmentListener mListener;

    public DeviceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DeviceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DeviceFragment newInstance(String param1, String param2) {
        DeviceFragment fragment = new DeviceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_device, container, false);
        ButterKnife.inject(this, view);
        adapter = new DeviceLinkedListAdapter(getContext());
        adapter.setClickListener(this);
        listLinked.setAdapter(adapter);
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnDeviceFragmentListener) {
            mListener = (OnDeviceFragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (int i = 0; i < linkedDevices.size(); i++) {
            BleDevice device = linkedDevices.get(i);
            if (device.bleLink != null)
                device.bleLink.dislink();
            if (device.heartBleLink != null)
                device.heartBleLink.dislink();
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        int position = v.getId();
        if (v instanceof Button) {
            String text = ((Button) v).getText().toString();
            switch (text) {
                case "连接":
                    break;
                case "正在连接":
                    break;
                case "断开连接":
                    BleDevice device = linkedDevices.get(position);
                    if (device.bleLink != null)
                        device.bleLink.dislink();
                    if (device.heartBleLink != null)
                        device.heartBleLink.dislink();
                    break;
                default:
                    break;
            }
        }
        if (v instanceof ImageView) {
            BleInfo info = adapter.getItem(position);
            if (info.state == BleDeviceState.DEVICE_STATE_LINKED) {
                BleDevice device = linkedDevices.get(position);
                if (device.bleLink != null) {

                }
                if (device.heartBleLink != null) {
                    if (device.heartBleLink.getHeartRateServer().bleHrsNotifEnable(!info.isNotify)) {
                        if (!info.isNotify)
                            MyUtil.showToast(getContext(), "通知打开");
                        else
                            MyUtil.showToast(getContext(), "通知关闭");
                        info.isNotify = !info.isNotify;
                        adapter.notifyDataSetChanged();
                    } else {
                        MyUtil.showToast(getContext(), "通知操作失败");
                    }
                }
            }
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnDeviceFragmentListener {
        // TODO: Update argument type and name
        void onDeviceStateChanged(ArrayList<BleDevice> linkedDevices, BleDeviceState state);
    }

    private void stateDeal(BleLink bleLink, HeartBleLink heartBleLink, BleDeviceState state) {
        getActivity().runOnUiThread(new BleStateRunnable(bleLink, heartBleLink, state) {
            @Override
            public void OnDeviceStateChanged(BleLink bleLink, BleDeviceState state) {
                if (adapter.getCount() > 0) {
                    adapter.getItem(bleLink.id).state = state;
                    adapter.notifyDataSetChanged();
                }
                if (state == BleDeviceState.DEVICE_STATE_DISLINK) {
                    linkedDevices.remove(bleLink.id);
                    adapter.getItem(bleLink.id).isNotify = false;
                    adapter.removeData(bleLink.id);
                    adapter.notifyDataSetChanged();
                    for (int i = bleLink.id; i < linkedDevices.size(); i++) {
                        BleDevice device = linkedDevices.get(i);
                        if (device.bleLink != null)
                            device.bleLink.id--;
                        if (device.heartBleLink != null)
                            device.heartBleLink.id--;
                    }
                    try {
                        Toast.makeText(getActivity(), "设备:" + bleLink.getName() + " " + bleLink.getAddress() + "断开连接", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {

                    }
                }
                if (state == BleDeviceState.DEVICE_STATE_LINKED) {
                    try {
                        Toast.makeText(getActivity(), "设备:" + bleLink.getName() + " " + bleLink.getAddress() + "已连接", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {

                    }
                }
                if (mListener != null) {
                    mListener.onDeviceStateChanged(linkedDevices, state);
                }
            }

            @Override
            public void OnDeviceStateChanged2(HeartBleLink bleLink, BleDeviceState state) {
                if (adapter.getCount() > 0) {
                    adapter.getItem(bleLink.id).state = state;
                    adapter.notifyDataSetChanged();
                }
                if (state == BleDeviceState.DEVICE_STATE_DISLINK) {
                    linkedDevices.remove(bleLink.id);
                    adapter.getItem(bleLink.id).isNotify = false;
                    adapter.removeData(bleLink.id);
                    adapter.notifyDataSetChanged();
                    for (int i = bleLink.id; i < linkedDevices.size(); i++) {
                        BleDevice device = linkedDevices.get(i);
                        if (device.bleLink != null)
                            device.bleLink.id--;
                        if (device.heartBleLink != null)
                            device.heartBleLink.id--;
                    }
                }
                if (mListener != null) {
                    mListener.onDeviceStateChanged(linkedDevices, state);
                }
            }
        });
    }

    private BleLink.BleListener bleListener = new BleLink.BleListener() {
        @Override
        public void OnDeviceStateChanged(BleLink bleLink, BleDeviceState state) {
            stateDeal(bleLink, null, state);
        }

        @Override
        public void OnDataReceived(BleLink bleLink, byte[] data) {

        }
    };
    private HeartBleLink.BleListener bleListener2 = new HeartBleLink.BleListener() {

        @Override
        public void OnDeviceStateChanged(HeartBleLink bleLink, BleDeviceState state) {
            stateDeal(null, bleLink, state);
        }

        @Override
        public void OnDataReceived(HeartBleLink bleLink, int hr_value, int[] rr_intervals, int rr_intervals_cnt) {

        }
    };

    /**
     * 添加连接设备
     */
    public void addDevice(BleInfo bleInfo, BluetoothDevice device) {
        BleDevice bleDevice = new BleDevice();
        if (bleInfo.type == 0) {
            bleDevice.type = BleDevice.DeviceType.Bong;
            bleDevice.bleLink = new BleLink(getContext());
            bleDevice.bleLink.id = linkedDevices.size();
            bleDevice.bleLink.addBleListener(bleListener);
            linkedDevices.add(bleDevice);
            adapter.addData(bleInfo);
            bleDevice.bleLink.link(device);
        } else {
            bleDevice.type = BleDevice.DeviceType.HeartReatBand;
            bleDevice.heartBleLink = new HeartBleLink(getContext());
            bleDevice.heartBleLink.id = linkedDevices.size();
            bleDevice.heartBleLink.addBleListener(bleListener2);
            linkedDevices.add(bleDevice);
            adapter.addData(bleInfo);
            bleDevice.heartBleLink.link(device);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 断开连接设备
     */
    public void removeDevice(BleInfo bleInfo) {

        int position = adapter.indexOfData(bleInfo);
        if (position < 0)
            return;
        BleDevice bleDevice = linkedDevices.get(position);
        if (bleDevice.bleLink != null)
            bleDevice.bleLink.dislink();
        if (bleDevice.heartBleLink != null)
            bleDevice.heartBleLink.dislink();
    }
}
